using GameConfig.item;
using GameLogic.GameLogic;
using System.Collections.Generic;
using TEngine;
using UnityEngine;

namespace GameLogic
{
    public class InventoryManager : Singleton<InventoryManager>
    {

        [Header("交易")]
        public int playerMoney=300;

        private Dictionary<string, List<InventoryItem>> boxDataDict = new Dictionary<string, List<InventoryItem>>();
        public int BoxDataAmount => boxDataDict.Count;

        public List<int> playerBag;

        //private void OnEnable()
        //{
        //    EventHandler.DropItemEvent += OnDropItemEvent;
        //    EventHandler.HarvestAtPlayerPosition += OnHarvestAtPlayerPosition;
        //    EventHandler.BuildFurnitureEvent += OnBuildFurnitureEvent;
        //    EventHandler.BaseBagOpenEvent += OnBaseBagOpenEvent;
        //    EventHandler.StartNewGameEvent += OnStartNewGameEvent;
        //}

        //private void OnDisable()
        //{
        //    EventHandler.DropItemEvent -= OnDropItemEvent;
        //    EventHandler.HarvestAtPlayerPosition -= OnHarvestAtPlayerPosition;
        //    EventHandler.BuildFurnitureEvent -= OnBuildFurnitureEvent;
        //    EventHandler.BaseBagOpenEvent -= OnBaseBagOpenEvent;
        //    EventHandler.StartNewGameEvent -= OnStartNewGameEvent;
        //}


        private void Start()
        {
        }

        private void OnStartNewGameEvent(int obj)
        {
            //playerBag = Instantiate(playerBagTemp);
            //playerMoney = Settings.playerStartMoney;
            //boxDataDict.Clear();
            //EventHandler.CallUpdateInventoryUI(InventoryLocation.Player, playerBag.itemList);
        }

        //private void OnBaseBagOpenEvent(SlotType slotType, InventoryBag_SO bag_SO)
        //{
        //    currentBoxBag = bag_SO;
        //}


        //private void OnBuildFurnitureEvent(int ID, Vector3 mousePos)
        //{
        //    RemoveItem(ID, 1);
        //    BluePrintDetails bluePrint = bluePrintData.GetBluePrintDetails(ID);
        //    foreach (var item in bluePrint.resourceItem)
        //    {
        //        RemoveItem(item.itemID, item.itemAmount);
        //    }
        //}

        //private void OnDropItemEvent(int ID, Vector3 pos, ItemType itemType)
        //{
        //    RemoveItem(ID, 1);
        //}

        //private void OnHarvestAtPlayerPosition(int ID)
        //{
        //    //是否已经有该物品
        //    var index = GetItemIndexInBag(ID);

        //    AddItemAtIndex(ID, index, 1);
        //    EventHandler.CallUpdateInventoryUI(InventoryLocation.Player, playerBag.itemList);
        //    //更新UI
        //}

        /// <summary>
        /// 通过ID返回物品信息
        /// </summary>
        /// <param name="ID">Item ID</param>
        /// <returns></returns>
        public ItemTb GetItemDetails(int ID)
        {
            return ConfigSystem.Instance.Tables.TbItem.GetOrDefault(ID);
        }

        /// <summary>
        /// 添加物品到Player背包里
        /// </summary>
        /// <param name="item"></param>
        /// <param name="toDestory">是否要销毁物品</param>
        public void AddItem(Item item, bool toDestory)
        {
            //是否已经有该物品
            var index = GetItemIndexInBag(item.itemID);

            AddItemAtIndex(item.itemID, index, 1);

            if (toDestory)
            {
                PoolManager.Instance.PushGameObject(item.gameObject);
                //Object.Destroy(item.gameObject);
            }

            GameEvent.Get<ILoginUI>().PlayerBagChange();
        }

        /// <summary>
        /// 检查背包是否有空位
        /// </summary>
        /// <returns></returns>
        private int CheckBagCapacity(out bool iscomFromSlot)
        {
            int index = -1;
            iscomFromSlot=false;
            if (UserInfo.Instance.GetUserSlotInfo() != null)
            {
                if (UserInfo.Instance.GetUserSlotInfo().Count < GameDataManager.Instance.defaultSlotCount)
                {
                    iscomFromSlot = true;
                    index = UserInfo.Instance.GetUserSlotInfo().Count;
                    return index;
                }
                foreach (var item in UserInfo.Instance.GetUserSlotInfo())
                {
                    if (item.Value.itemID == 0)
                    {
                        index = item.Key;
                        iscomFromSlot = true;
                        return index;
                    }

                }
            }
            if (UserInfo.Instance.GetUserBagInfo() != null)
            {
                if (UserInfo.Instance.GetUserBagInfo().Count < GameDataManager.Instance.defaultBagCount)
                {
                    index = UserInfo.Instance.GetUserBagInfo().Count;
                    return index;
                }
                foreach (var item in UserInfo.Instance.GetUserBagInfo())
                {
                    if (item.Value.itemID == 0)
                    {
                        index = item.Key;
                        return index;
                    }

                }
            }
            return index;
        }

        /// <summary>
        /// 通过物品ID找到背包已有物品位置
        /// </summary>
        /// <param name="ID">物品ID</param>
        /// <returns>-1则没有这个物品否则返回序号</returns>
        private int GetItemIndexInBag(int ID)
        {
            if (UserInfo.Instance.GetUserBagInfo() != null)
            {
                foreach (KeyValuePair<int, InventoryItem> kv in UserInfo.Instance.GetUserBagInfo())
                {
                    if (kv.Value.itemID == ID)
                    {
                        return kv.Key;
                    }
                }
            }
            if (UserInfo.Instance.GetUserSlotInfo() != null)
            {
                foreach (KeyValuePair<int, InventoryItem> kv in UserInfo.Instance.GetUserSlotInfo())
                {
                    if (kv.Value.itemID == ID)
                    {
                        return kv.Key;
                    }
                }
            }

            return -1;
        }

        /// <summary>
        /// 在指定背包序号位置添加物品
        /// </summary>
        /// <param name="ID">物品ID</param>
        /// <param name="index">序号</param>
        /// <param name="amount">数量</param>
        private void AddItemAtIndex(int ID, int index, int amount)
        {
            bool iscomFromSlot = false;
            int newItemIndex = CheckBagCapacity(out iscomFromSlot);
            if (index == -1 && newItemIndex != -1)    //背包没有这个物品 同时背包有空位
            {
                var item = new InventoryItem { itemID = ID, itemAmount = amount,itemPos=newItemIndex };
                if (iscomFromSlot)
                {
                    UserInfo.Instance.GetUserSlotInfo()[newItemIndex]= item;
                }
                else
                {
                    UserInfo.Instance.GetUserBagInfo()[newItemIndex] = item;
                }
            }
            else    //背包有这个物品
            {
                int currentAmount;
                if (UserInfo.Instance.GetUserSlotInfo().ContainsKey(index))
                {
                    if (UserInfo.Instance.GetUserSlotInfo()[index] != null&& UserInfo.Instance.GetUserSlotInfo()[index].itemID== ID)
                    {
                        currentAmount = UserInfo.Instance.GetUserSlotInfo()[index].itemAmount + amount;
                        UserInfo.Instance.GetUserSlotInfo()[index].itemAmount = currentAmount;
                    }
                }
                if (UserInfo.Instance.GetUserBagInfo().ContainsKey(index))
                {
                    if (UserInfo.Instance.GetUserBagInfo()[index] != null && UserInfo.Instance.GetUserBagInfo()[index].itemID == ID)
                    {
                        currentAmount = UserInfo.Instance.GetUserBagInfo()[index].itemAmount + amount;
                        UserInfo.Instance.GetUserBagInfo()[index].itemAmount = currentAmount;
                    }
                }

            }
            //EventHandler.CallUpdateInventoryUI(InventoryLocation.Player, UserInfo.Instance.GetUserBagInfo());
        }

        /// <summary>
        /// Player物品框范围内交换物品
        /// </summary>
        /// <param name="fromIndex">起始序号</param>
        /// <param name="targetIndex">目标数据序号</param>
        public void SwapSlotUIItem(int fromIndex, int targetIndex)
        {
            InventoryItem currentItem = UserInfo.Instance.playerInfo.itemsSlot[fromIndex];
            InventoryItem targetItem = UserInfo.Instance.playerInfo.itemsSlot[targetIndex];

            if (targetItem.itemID != 0)
            {
                UserInfo.Instance.playerInfo.itemsSlot[fromIndex] = targetItem;
                UserInfo.Instance.playerInfo.itemsSlot[fromIndex].itemPos=fromIndex;
                UserInfo.Instance.playerInfo.itemsSlot[targetIndex] = currentItem;
                UserInfo.Instance.playerInfo.itemsSlot[targetIndex].itemPos = targetIndex;
            }
            else
            {
                UserInfo.Instance.playerInfo.itemsSlot[targetIndex] = currentItem;
                UserInfo.Instance.playerInfo.itemsSlot[targetIndex].itemPos=targetIndex;
                UserInfo.Instance.playerInfo.itemsSlot[fromIndex] = new InventoryItem();
                UserInfo.Instance.playerInfo.itemsSlot[fromIndex].itemPos = fromIndex;
            }
            GameEvent.Get<ILoginUI>().PlayerBagChange();
        }

        /// <summary>
        /// 跨背包交换数据
        /// </summary>
        /// <param name="locationFrom"></param>
        /// <param name="fromIndex"></param>
        /// <param name="locationTarget"></param>
        /// <param name="targetIndex"></param>
        //public void SwapItem(InventoryLocation locationFrom, int fromIndex, InventoryLocation locationTarget, int targetIndex)
        //{
        //    var currentList = GetItemList(locationFrom);
        //    var targetList = GetItemList(locationTarget);

        //    InventoryItem currentItem = currentList[fromIndex];

        //    if (targetIndex < targetList.Count)
        //    {
        //        InventoryItem targetItem = targetList[targetIndex];

        //        if (targetItem.itemID != 0 && currentItem.itemID != targetItem.itemID)  //有不相同的两个物品
        //        {
        //            currentList[fromIndex] = targetItem;
        //            targetList[targetIndex] = currentItem;
        //        }
        //        else if (currentItem.itemID == targetItem.itemID) //相同的两个物品
        //        {
        //            targetItem.itemAmount += currentItem.itemAmount;
        //            targetList[targetIndex] = targetItem;
        //            currentList[fromIndex] = new InventoryItem();
        //        }
        //        else    //目标空格子
        //        {
        //            targetList[targetIndex] = currentItem;
        //            currentList[fromIndex] = new InventoryItem();
        //        }
        //        EventHandler.CallUpdateInventoryUI(locationFrom, currentList);
        //        EventHandler.CallUpdateInventoryUI(locationTarget, targetList);
        //    }
        //}

        /// <summary>
        /// 根据位置返回背包数据列表
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        //private List<InventoryItem> GetItemList(InventoryLocation location)
        //{
        //    return location switch
        //    {
        //        InventoryLocation.Player => playerBag.itemList,
        //        InventoryLocation.Box => currentBoxBag.itemList,
        //        _ => null
        //    };
        //}

        /// <summary>
        /// 移除指定数量的背包物品
        /// </summary>
        /// <param name="ID">物品ID</param>
        /// <param name="removeAmount">数量</param>
        //private void RemoveItem(int ID, int removeAmount)
        //{
        //    var index = GetItemIndexInBag(ID);

        //    if (playerBag.itemList[index].itemAmount > removeAmount)
        //    {
        //        var amount = playerBag.itemList[index].itemAmount - removeAmount;
        //        var item = new InventoryItem { itemID = ID, itemAmount = amount };
        //        playerBag.itemList[index] = item;
        //    }
        //    else if (playerBag.itemList[index].itemAmount == removeAmount)
        //    {
        //        var item = new InventoryItem();
        //        playerBag.itemList[index] = item;
        //    }
        //    EventHandler.CallUpdateInventoryUI(InventoryLocation.Player, playerBag.itemList);
        //}


        /// <summary>
        /// 交易物品
        /// </summary>
        /// <param name="itemDetails">物品信息</param>
        /// <param name="amount">交易数量</param>
        /// <param name="isSellTrade">是否卖东西</param>
        //public void TradeItem(ItemDetails itemDetails, int amount, bool isSellTrade)
        //{
        //    int cost = itemDetails.itemPrice * amount;
        //    //获得物品背包位置
        //    int index = GetItemIndexInBag(itemDetails.itemID);

        //    if (isSellTrade)    //卖
        //    {
        //        if (playerBag.itemList[index].itemAmount >= amount)
        //        {
        //            cost = (int)(cost * itemDetails.sellPercentage);
        //            playerMoney += cost;
        //            RemoveItem(itemDetails.itemID, amount);
        //            //卖出总价

        //        }
        //    }
        //    else if (playerMoney - cost >= 0)   //买
        //    {
        //        playerMoney -= cost;
        //        if (CheckBagCapacity())
        //        {
        //            AddItemAtIndex(itemDetails.itemID, index, amount);
        //        }

        //    }
        //}

        /// <summary>
        /// 检查建造资源物品库存
        /// </summary>
        /// <param name="ID">图纸ID</param>
        /// <returns></returns>
        //public bool CheckStock(int ID)
        //{
        //    var bluePrintDetails = bluePrintData.GetBluePrintDetails(ID);

        //    foreach (var resourceItem in bluePrintDetails.resourceItem)
        //    {
        //        var itemStock = playerBag.GetInventoryItem(resourceItem.itemID);
        //        if (itemStock.itemAmount >= resourceItem.itemAmount)
        //        {
        //            continue;
        //        }
        //        else return false;
        //    }
        //    return true;
        //}

        /// <summary>
        /// 查找箱子数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        //public List<InventoryItem> GetBoxDataList(string key)
        //{
        //    if (boxDataDict.ContainsKey(key))
        //        return boxDataDict[key];
        //    return null;
        //}
        /// <summary>
        /// 加入箱子数据字典
        /// </summary>
        /// <param name="box"></param>
        //public void AddBoxDataDict(Box box)
        //{
        //    var key = box.name + box.index;
        //    if (!boxDataDict.ContainsKey(key))
        //        boxDataDict.Add(key, box.boxBagData.itemList);
        //    Debug.Log(key);
        //}

        //public GameSaveData GenerateSaveData()
        //{
        //    GameSaveData saveData = new GameSaveData();
        //    saveData.playerMoney= playerMoney;
        //    saveData.inventoryDict = new Dictionary<string, List<InventoryItem>>();
        //    saveData.inventoryDict.Add(playerBag.name, playerBag.itemList);
        //    foreach (var item in boxDataDict)
        //    {
        //        saveData.inventoryDict.Add(item.Key, item.Value);
        //    }
        //    return saveData;
        //}

        //public void RestoreData(GameSaveData saveData)
        //{
        //    this.playerMoney = saveData.playerMoney;
        //    playerBag = Instantiate(playerBagTemp);
        //    playerBag.itemList = saveData.inventoryDict[playerBag.name];

        //    foreach (var item in saveData.inventoryDict)
        //    {
        //        if (boxDataDict.ContainsKey(item.Key))
        //        {
        //            boxDataDict[item.Key] = item.Value;
        //        }
        //    }

        //    EventHandler.CallUpdateInventoryUI(InventoryLocation.Player, playerBag.itemList);
        //}
    }
}